package cn.yh.register.order.service.impl;

import cn.yh.register.client.hosp.HospFeignClient;
import cn.yh.register.common.exception.RegisterException;
import cn.yh.register.common.helper.HttpRequestHelper;
import cn.yh.register.common.result.ResultCodeEnum;
import cn.yh.register.enums.OrderStatusEnum;
import cn.yh.register.enums.PaymentStatusEnum;
import cn.yh.register.enums.PaymentTypeEnum;
import cn.yh.register.model.order.OrderInfo;
import cn.yh.register.model.order.PaymentInfo;
import cn.yh.register.model.order.RefundInfo;
import cn.yh.register.order.mapper.PaymentInfoMapper;
import cn.yh.register.order.service.OrderService;
import cn.yh.register.order.service.PaymentService;
import cn.yh.register.vo.order.SignInfoVo;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.collections4.map.HashedMap;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class PaymentServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentService {


    @Autowired
    private PaymentService paymentService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private HospFeignClient hospFeignClient;

    /**
     * 保存支付成功的订单信息
     * @param orderInfo 封装的订单信息
     * @param paymentType 支付类型
     */
    @Override
    public void savePaymentInfo(OrderInfo orderInfo, Integer paymentType) {
        //1.先查询数据库中是否有
        Integer count = baseMapper.selectCount(new LambdaQueryWrapper<PaymentInfo>().
                 eq(PaymentInfo::getOrderId, orderInfo.getId())
                .eq(PaymentInfo::getPaymentType, paymentType));
        if (count <= 0){
            //2.数据库中没有 插入
            PaymentInfo paymentInfo = new PaymentInfo();
            paymentInfo.setOutTradeNo(orderInfo.getOutTradeNo());
            paymentInfo.setOrderId(orderInfo.getId());
            paymentInfo.setPaymentType(PaymentTypeEnum.WEIXIN.getStatus());
            paymentInfo.setTotalAmount(orderInfo.getAmount());
            String subject = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd")
                    + "|" + orderInfo.getHosname() + "|" + orderInfo.getDepname() + "|" + orderInfo.getTitle();
            paymentInfo.setSubject(subject);
            //支付中
            paymentInfo.setPaymentStatus(PaymentStatusEnum.UNPAID.getStatus());
            baseMapper.insert(paymentInfo);
        }
    }

    /**
     * 支付成功 更新支付记录，更新订单状态，调医院系统更新订单状态
     * @param outTradeNo  订单编号
     * @param paymentType 支付类型
     * @param resultMap   调医院系统传的数据更新订单状态
     */
    @Override
    public void paySuccess(String outTradeNo, Integer paymentType, Map<String, String> resultMap) {
        //1.更新支付记录
        //1.1查询到支付记录表
        PaymentInfo paymentInfo = this.paymentInfo(outTradeNo, paymentType);
        if (paymentInfo == null){
            throw new RegisterException(ResultCodeEnum.PARAM_ERROR);
        }
        if (!Objects.equals(paymentInfo.getPaymentStatus(), PaymentStatusEnum.UNPAID.getStatus())) {
            return;
        }
        //2.更新支付记录
        paymentInfo.setTradeNo(resultMap.get("transaction_id")); // 微信的交易流水号
        paymentInfo.setPaymentStatus(PaymentStatusEnum.PAID.getStatus());
        paymentInfo.setCallbackTime(new Date());
        paymentInfo.setCallbackContent(JSONObject.toJSONString(resultMap));
        paymentInfo.setUpdateTime(new Date());
        baseMapper.updateById(paymentInfo);
        //3.更新订单状态
        OrderInfo orderInfo = orderService.getById(paymentInfo.getOrderId());
        orderInfo.setOrderStatus(OrderStatusEnum.PAID.getStatus());
        orderInfo.setUpdateTime(new Date());
        orderService.updateById(orderInfo);
        // 告诉医院系统支付结果
        SignInfoVo signInfoVo = hospFeignClient.getSignInfoVo(orderInfo.getHoscode());
        if (signInfoVo == null) {
            throw new RegisterException(ResultCodeEnum.DATA_ERROR);
        }
        Map<String, Object> paramMap = new HashedMap<>();
        paramMap.put("hoscode", orderInfo.getHoscode());
        paramMap.put("hosRecordId", orderInfo.getHosRecordId());
        paramMap.put("timestamp", HttpRequestHelper.getTimestamp());
        paramMap.put("sign", HttpRequestHelper.getSign(paramMap, signInfoVo.getSignKey()));
        // 调医院系统更新订单
        JSONObject jsonObject = HttpRequestHelper.sendRequest(paramMap, signInfoVo.getApiUrl() + "/order/updatePayStatus");
        if (jsonObject.getInteger("code") != 200) {
            throw new RegisterException(jsonObject.getString("message"), ResultCodeEnum.FAIL.getCode());
        }
    }

    /**
     * 查支付记录
     * @param outTradeNo 交易号
     * @param paymentType 支付类型
     * @return 支付记录
     */
    public PaymentInfo paymentInfo(String outTradeNo,Integer paymentType){
        return baseMapper.selectOne(new LambdaQueryWrapper<PaymentInfo>()
                .eq(PaymentInfo::getOutTradeNo, outTradeNo)
                .eq(PaymentInfo::getPaymentType, paymentType));
    }
}
